import { constantRoutes } from '@/router/index'
import { getRouters } from '@/api/menu'
import { dyncRoutes, filterAsyncRouter } from '@/utils/routes'
import { find, get } from 'lodash'
const router: any = {
  namespace: true,
  state: {
    currentMenu: '/science',
    routes: [],
    addRoutes: [],
    routesName: '',
    microApps: [],
    microMenu: [],
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.routes = routes
    },
    GET_ROUTES: (state) => {
      if (!localStorage.getItem('routes')) return
    },
    SET_ROUTES_NAME: (state, name) => {
      state.routesName = name
    },
    SET_MICRO_MENU: (state, menu) => {
      state.microMenu = menu
    },
    SET_CURRENT_MENU:(state, current) => {
      state.currentMenu = current
    },
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise((resolve) => {
        // 向后端请求路由数据
        getRouters().then((res) => {
          res.data.data.forEach((route) => {
            if (route.children) {
              route.redirect = handleRedirect('', route)
            }
          })
          localStorage.setItem('routes', JSON.stringify(res.data.data))
          const accessedRoutes = dyncRoutes(JSON.parse(JSON.stringify(res.data.data)))
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        })
      })
    },
  },
}
const handleRedirect = (parent, routes) => {
  // console.log(`${parent}/${routes.path}`);
  if (routes.children) {
    let i = 0
    routes.children.some((item, index) => {
      if (item.frameFlag) {
        i = index
        return true
      }
    })
    return handleRedirect(`${parent}/${routes.path}`, routes.children[i])
  } else {
    return `${parent}/${routes.path}`
  }
}
export default router
